goog.provide('mitel.messaging');

goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.net.xpc.CrossPageChannel');
goog.require('goog.style');
goog.require('goog.net.cookies');

goog.require('mitel.deployment');

var channel;

mitel.messaging.MOBILE = false;

mitel.messaging.init = function(connect_callback) {
  var container = goog.dom.createElement('div');
  goog.style.showElement(container, false);

  goog.dom.appendChild(document.body, container);

  var cfg = {};

  var ownUri = new goog.Uri(window.location.href);
  var peerUri = new goog.Uri(mitel.deployment.socket_server);

  var localPollUri = peerUri.resolve(new goog.Uri('static/blank.html'));
  var peerPollUri = peerUri.resolve(new goog.Uri('static/blank.html'));

  cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] = localPollUri.toString();
  cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] = peerPollUri.toString();

  var peerUri = peerUri.resolve(new goog.Uri('static/inner.html'));
  cfg[goog.net.xpc.CfgFields.PEER_URI] = peerUri;

  // Create the channel.
  channel = new goog.net.xpc.CrossPageChannel(cfg);

  channel.createPeerIframe(container);
  
  channel.registerService('cookie:sentMobile', mitel.messaging.recieveMobile);
  
  channel.connect(function() {
     mitel.messaging.requestMobile();
     
     if (connect_callback) {
        connect_callback();
     }
  });
  
  return channel;
  
};


mitel.messaging.recieveMobile = function(isMobile) {
   if (isMobile === true || isMobile === 'true') {
      isMobile = true;
   } else {
      isMobile = false;
   }
   mitel.messaging.MOBILE = isMobile;
}

mitel.messaging.setMobile = function(isMobile) {
   channel.send('cookie:setMobile', isMobile);
}

mitel.messaging.getMobile = function() {
   return mitel.messaging.MOBILE;
}

mitel.messaging.requestMobile = function() {
   channel.send('cookie:requestMobile');
}


goog.provide('mitel.messaging.inner');

mitel.messaging.inner.init_child = function() {
  // Get the channel configuration from the URI parameter.
  var cfg = goog.json.parse((new goog.Uri(window.location.href)).getParameterValue('xpc'));

  // Create the channel.
  channel = new goog.net.xpc.CrossPageChannel(cfg);
  
  channel.registerService('cookie:requestMobile', mitel.messaging.inner.sendMobile);
  channel.registerService('cookie:setMobile', mitel.messaging.inner.setMobile);

  channel.connect(function() {
  });
};

mitel.messaging.inner.setMobile = function(isMobile) {
   goog.net.cookies.set('isMobile', isMobile);
   channel.send('cookie:sentMobile', isMobile);
}

mitel.messaging.inner.getMobile = function() {
   var isMobile = goog.net.cookies.get('isMobile');
   if (!isMobile) {
      mitel.messaging.inner.setMobile(false);
      return mitel.messaging.inner.getMobile();
   }
   
   return isMobile;
}

mitel.messaging.inner.sendMobile = function() {
   var isMobile = mitel.messaging.inner.getMobile();
   
   channel.send('cookie:sentMobile', isMobile);
}
